package com.iye.puretennis.fragment;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.Context;
import android.os.Bundle;
import android.view.*;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.*;
import com.iye.puretennis.custom.draggablegridview.BaseDynamicGridAdapter;
import com.iye.puretennis.domain.Appointment;
import com.iye.puretennis.domain.ListItem;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.helper.Session;
import com.iye.puretennis.utils.JsonUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/12/16
 * Time: 14:01
 */
public class MyAppointmentFragment extends TabFragment {

    private String appointmentGuid;

    protected Appointment appointment = new Appointment();

    private LinkedList<ListItem> participants = new LinkedList<ListItem>();

    private LinkedList<ListItem> invitations = new LinkedList<ListItem>();

    private LinkedList<ListItem> requests = new LinkedList<ListItem>();

    private AppointmentAdapter participantsAdapter;

    private AppointmentAdapter invitationsAdapter;

    private AppointmentAdapter requestsAdapter;

    private HorizontalListView invitationsView;

    private HorizontalListView participantsView;

    private HorizontalListView requestsView;

    private int listViewWidth;

    private int listViewHeight;

    private DragEventListener mDragListener;

    private DragLongClickListener dragLongClickListener;


    public static final int dividerWidth = 5;

    public static final String TAG = "my_appointment";


    @Override
    public void onCustomCreateView(LayoutInflater inflater) {

        fragmentActivity.hideTabBar();

        Session session = Session.newSession();

        appointmentGuid = (String) session.get("appointmentGuid");

        listViewWidth =  (width - dividerWidth * 3 - 15) / 5 + 10;

        listViewHeight = listViewWidth + 40;

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fragmentActivity.showTabBar();
                onBackPressed();
            }
        });
//
//        invitations.add(new ListItem("1", "1", "so"));
//        invitations.add(new ListItem("2", "2", "like"));
//        invitations.add(new ListItem("3", "3", "do"));
//        invitations.add(new ListItem("3", "3", "add"));
//        invitations.add(new ListItem("3", "3", "cool"));

        invitationsAdapter = new AppointmentAdapter(fragmentActivity, invitations, 5, 1);


//        participants.add(new ListItem("4", "4", "what"));
//        participants.add(new ListItem("5", "5", "that"));
//        participants.add(new ListItem("6", "6", "need"));
//        participants.add(new ListItem("7", "7", "main"));

        participantsAdapter = new AppointmentAdapter(fragmentActivity, participants, 5, 2);

//
//        requests.add(new ListItem("8", "8", "appointment"));
//        requests.add(new ListItem("9", "9", "dota"));
//        requests.add(new ListItem("10", "10", "ten"));
//        requests.add(new ListItem("11", "11", "kunka"));
//        requests.add(new ListItem("12", "12", "sven"));
//        requests.add(new ListItem("13", "13", "lili"));

        requestsAdapter = new AppointmentAdapter(fragmentActivity, requests, 5, 3);


        HuaWenHuPoTextView actionView = (HuaWenHuPoTextView) mainView.findViewById(R.id.action_text);

        actionView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopup();
            }
        });

        invitationsView = (HorizontalListView) mainView.findViewById(R.id.invitations_view);

        invitationsView.getLayoutParams().height = listViewHeight;

        invitationsView.setAdapter(invitationsAdapter);

        participantsView = (HorizontalListView) mainView.findViewById(R.id.participants_view);

        participantsView.getLayoutParams().height = listViewHeight;

        participantsView.setAdapter(participantsAdapter);

        requestsView = (HorizontalListView) mainView.findViewById(R.id.requests_view);

        requestsView.getLayoutParams().height = listViewHeight;

        requestsView.setAdapter(requestsAdapter);


    }

    public void accept() {

        acceptRequests();

    }


    @SuppressLint("NewApi")
    protected class DragEventListener implements View.OnDragListener {


        // 该方法由系统调用，当有拖拽事件发生时
        @SuppressLint("ShowToast")
        public boolean onDrag(View v, DragEvent event) {
            // 定义一个变量来存储通过事件传递的action类型
            final int action = event.getAction();
            // 每个事件的处理
            switch (action) {

                case DragEvent.ACTION_DRAG_STARTED:
                    // 确定是否这个视图（View）可以接收拖拽的数据类型
                    if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {

                        // 通过返回true来表明View可以接收拖拽数据
                        return (true);

                    } else {
                        // 返回false. 在当前是拖拽和落下操作时，视图（View）将不再接收
                        // 事件直到发送ACTION_DRAG_ENDED
                        return (false);
                    }

                case DragEvent.ACTION_DRAG_ENTERED:

                    return (true);

                case DragEvent.ACTION_DRAG_LOCATION:
                    // 忽略该事件
                    return (true);

                case DragEvent.ACTION_DRAG_EXITED:

                    return (true);

                case DragEvent.ACTION_DROP:
                    // 获得item包括拖拽数据
                    ClipData.Item item = event.getClipData().getItemAt(0);
                    // 从item获得文本数据
                    CharSequence dragData = item.getText();

                    acceptRequest(Integer.parseInt(dragData.toString()));


                    // 返回true. DragEvent.getResult()将会返回true.
                    return (true);

                case DragEvent.ACTION_DRAG_ENDED:


                    return (true);

                // 其他未知的action.
                default:

                    break;
            }

            return true;
        }
    }


    private void delete(final String appointmentGuid) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                JSONObject profileJsonObj = new JSONObject();

                try {
                    profileJsonObj.put("guid", appointmentGuid);
                    StringEntity paramEntity = new StringEntity(profileJsonObj.toString(), Constant.CHARSET_UTF8);
                    String result = ServerAccessHelper.queryStringForDelete(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT), token.getToken(), paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                goFragment(getSourceId(), MyAppointmentsFragment.TAG, MyAppointmentsFragment.class, null, false);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }


            }
        }).start();
    }


    private void appointmentRender(final UserToken token) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                json = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT) + "/" + appointmentGuid, token.getToken());
                getActivity().runOnUiThread(uiUpdate);
            }
        }).start();
    }

    private Runnable uiUpdate = new Runnable() {
        @Override
        public void run() {
            if (!Constant.RESPONSE_BADLY.equals(json)) {
                appointment = JsonUtils.toAppointment(json, token.getGuid());
                if (appointment != null) {
                    HuaWenHuPoTextView invitationText = (HuaWenHuPoTextView) mainView.findViewById(R.id.invitation_text);
                    if(appointment.getInvitations().isEmpty()) {
                         invitationText.setVisibility(View.GONE);
                         invitationsView.setVisibility(View.GONE);
                    }else{
                        invitationText.setVisibility(View.VISIBLE);
                        invitationsView.setVisibility(View.VISIBLE);
                        invitationsAdapter.set(appointment.getInvitations());
                    }
                    participantsAdapter.set(appointment.getParticipants());
                    HuaWenHuPoTextView requestText = (HuaWenHuPoTextView) mainView.findViewById(R.id.request_text);
                    if(appointment.getRequests().isEmpty()){
                        requestText.setVisibility(View.GONE);
                        requestsView.setVisibility(View.GONE);
                    }else{
                        requestText.setVisibility(View.VISIBLE);
                        requestsView.setVisibility(View.VISIBLE);
                        requestsAdapter.set(appointment.getRequests());

                    }
                    headerText.setText(appointment.getLocation());

                    HuaWenHuPoTextView timeView = (HuaWenHuPoTextView) mainView.findViewById(R.id.time);
                    timeView.setText(appointment.getPeriods());

                    HuaWenHuPoTextView noteView = (HuaWenHuPoTextView) mainView.findViewById(R.id.note);
                    noteView.setText(appointment.getPaymentWay() + "\n\n" + appointment.getNote());
                }
            }
        }
    };


    private void showUserInfo(ListItem listItem) {
        Bundle bundle = new Bundle();
        String userGuid = listItem.getGuid3();
        bundle.putString("userGuid", userGuid);
        goFragment(R.id.my_appointment, UserInfoFragment.TAG, UserInfoFragment.class, bundle, false, userGuid);
    }


    class AppointmentAdapter extends BaseDynamicGridAdapter {

        private List<Integer> selection = new ArrayList<Integer>();

        //1 invitations,2 participants,3 requests
        private int type;


        public AppointmentAdapter(Context context, List<?> items1, int columnCount, int type) {
            super(context, items1, columnCount);
            this.type = type;
        }

        @Override
        public View getView(final int position, View view, ViewGroup viewGroup) {

            final ListItem listItem = (ListItem) getItem(position);
            ImageView userPhotoView;
            TextView nicknameView;
            ImageView selectedIconView;

            ViewCache viewCache;
            if (view == null) {
                view = LayoutInflater.from(getContext()).inflate(R.layout.user_image, null);
                userPhotoView = (ImageView) view.findViewById(R.id.user_photo);
                nicknameView = (TextView) view.findViewById(R.id.user_nickname);
                selectedIconView = (ImageView) view.findViewById(R.id.icon_yes);
                viewCache = new ViewCache(userPhotoView, nicknameView, selectedIconView);
                view.setTag(viewCache);
            } else {
                viewCache = (ViewCache) view.getTag();
                userPhotoView = viewCache.userPhotoView;
                nicknameView = viewCache.nameView;
                selectedIconView = viewCache.selectedIconView;
            }
            userPhotoView.getLayoutParams().width = listViewWidth;
            userPhotoView.getLayoutParams().height = listViewWidth;
            String userGuid = listItem.getGuid3();
            boolean me = token.getGuid().equals(userGuid);
            loadUserImage(userGuid,userPhotoView);
            nicknameView.getLayoutParams().width = listViewWidth;
            nicknameView.setText(me?Constant.ME:listItem.getName());
            selectedIconView.getLayoutParams().width = listViewWidth / 3;
            selectedIconView.getLayoutParams().height = listViewWidth / 3;
            if (selection.contains(position)) {
                selectedIconView.setVisibility(View.VISIBLE);
            } else {
                selectedIconView.setVisibility(View.INVISIBLE);
            }

            if (type == 3) {

                dragLongClickListener = new DragLongClickListener(position);

                //添加长按事件
                view.setOnLongClickListener(dragLongClickListener);

                // 创建一个拖拽的事件监听器
                mDragListener = new DragEventListener();

                requestsView.setChildTouchListener(view);

                // 拖拽反应区域
                // 为该区域添加拖动事件监听器
                participantsView.setOnDragListener(mDragListener);
            } else if (type == 2) {
                participantsView.setChildTouchListener(view);
            } else {
                invitationsView.setChildTouchListener(view);
            }

            if (!me) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (type == 1) {
                            requestsAdapter.clearSelection();
                            participantsAdapter.clearSelection();
                            invitationsAdapter.selectItem(position);
                        } else if (type == 2) {
                            requestsAdapter.clearSelection();
                            invitationsAdapter.clearSelection();
                            participantsAdapter.selectItem(position);
                        } else {
                            participantsAdapter.clearSelection();
                            invitationsAdapter.clearSelection();
                            requestsAdapter.selectItem(position);
                        }
                    }
                });
            }


            return view;
        }

        public List<ListItem> getSelection() {
            List<ListItem> listItems = new ArrayList<ListItem>();
            for (Integer position : selection) {
                listItems.add((ListItem) getItem(position));
            }
            return listItems;
        }

        public void selectItem(int position) {
            if (selection.contains(position)) {
                removeSelection(position);
            } else {
                addSelection(position);
            }
            notifyDataSetChanged();
        }

        private void removeSelection(int position) {
            selection.remove(Integer.valueOf(position));
        }

        private void addSelection(int position) {
            selection.add(position);
        }

        public void clearSelection() {
            selection.clear();
            notifyDataSetChanged();
        }
    }

    class ViewCache {

        private ImageView userPhotoView;

        private TextView nameView;

        private ImageView selectedIconView;


        public ViewCache(ImageView userPhotoView, TextView nameView, ImageView selectedIconView) {
            this.userPhotoView = userPhotoView;
            this.nameView = nameView;
            this.selectedIconView = selectedIconView;
        }
    }


    @Override
    public int getViewId() {
        return R.layout.my_appointment;
    }

    @Override
    public int getSourceId() {
        return R.id.my_appointment;
    }

    @Override
    public void updateUI() {
        appointmentRender(token);
    }

    private void acceptRequest(final int position) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                final ListItem listItem = (ListItem) requestsAdapter.getItem(position);
                String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT_REQUEST_ACCEPT) + "/" + listItem.getGuid2(), token.getToken());
                if (!Constant.RESPONSE_BADLY.equals(result)) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            requestsAdapter.remove(listItem);
                            participantsAdapter.add(listItem);
                        }
                    });
                }

            }
        }).start();

    }

    private void acceptRequests() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ListItem> listItems = requestsAdapter.getSelection();
                for (final ListItem listItem : listItems) {
                    String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT_REQUEST_ACCEPT) + "/" + listItem.getGuid2(), token.getToken());
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                requestsAdapter.remove(listItem);
                                participantsAdapter.add(listItem);
                            }
                        });
                    }
                }
            }
        }).start();
    }


    public void remove(int type) {
        if (type == 1) {
            removeInvitation();
        } else if (type == 2) {
            removeParticipant();
        } else {
            rejectRequest();
        }
    }

    public int getType() {
        if (!invitationsAdapter.selection.isEmpty()) {
            return 1;
        } else if (!participantsAdapter.selection.isEmpty()) {
            return 2;
        } else if (!requestsAdapter.selection.isEmpty()) {
            return 3;
        } else {
            return -1;
        }
    }

    private void removeInvitation() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ListItem> listItems = invitationsAdapter.getSelection();
                for (final ListItem currentInvitation : listItems) {
                    String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT_INVITATION_REMOVE) + "/" + currentInvitation.getGuid2(), token.getToken());
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                invitationsAdapter.remove(currentInvitation);
                            }
                        });
                    }
                }
                invitationsAdapter.clearSelection();
            }
        }).start();
    }


    private void rejectRequest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ListItem> listItems = requestsAdapter.getSelection();
                for (final ListItem currentRequest : listItems) {
                    String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT_REQUEST_REJECT) + "/" + currentRequest.getGuid2(), token.getToken());
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                requestsAdapter.remove(currentRequest);
                            }
                        });
                    }
                }
            }
        }).start();
    }

    private void removeParticipant() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ListItem> listItems = participantsAdapter.getSelection();
                for (final ListItem currentJoiner : listItems) {
                    JSONObject jsonObj = new JSONObject();
                    try {
                        jsonObj.put("appointmentGuid", currentJoiner.getGuid());
                        jsonObj.put("participantGuid", currentJoiner.getGuid2());
                        StringEntity paramEntity = new StringEntity(jsonObj.toString(), Constant.CHARSET_UTF8);
                        String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT_PARTICIPANTS_REMOVE), token.getToken(), paramEntity);
                        if (!result.equals(Constant.RESPONSE_BADLY)) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    participantsAdapter.remove(currentJoiner);
                                }
                            });
                        }

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }
        }).start();
    }

    private void showPopup() {
        PopupWindow popupWindow = new AppointmentActionWindow(this);
        popupWindow.showAtLocation(mainView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}
